package com.hwpt.handler;

import com.hwpt.enumeration.ResultCode;
import com.hwpt.exception.AuthException;
import com.hwpt.exception.BaseException;
import com.hwpt.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * 全局异常处理器 - 简化版
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BaseException.class)
    public Result<?> handleBusinessException(BaseException e) {
        log.warn("业务异常: {}", e.getMessage());
        return Result.error(ResultCode.BUSINESS_ERROR, e.getMessage());
    }

    /**
     * 处理认证异常
     */
    @ExceptionHandler(AuthException.class)
    public Result<?> handleAuthException(AuthException e) {
        log.warn("认证异常: {}", e.getMessage());
        return Result.error(ResultCode.UNAUTHORIZED, e.getMessage());
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler({
        MethodArgumentNotValidException.class,
        ConstraintViolationException.class
    })
    public Result<?> handleValidationException(Exception e) {
        log.warn("参数校验异常: {}", e.getMessage());
        return Result.error(ResultCode.VALIDATION_ERROR, "参数校验失败");
    }

    /**
     * 处理所有其他异常
     */
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e) {
        log.error("系统异常: {}", e.getMessage(), e);
        return Result.error(ResultCode.INTERNAL_SERVER_ERROR, "系统繁忙，请稍后再试");
    }
}